<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
use tool\Auth;

/**
 * 生产密码
 * @param $password
 * @return string
 */
function makePassword($password) {

    return md5($password . config('whisper.salt'));
}

/**
 * 检测密码
 * @param $dbPassword
 * @param $inPassword
 * @return bool
 */
function checkPassword($inPassword, $dbPassword) {
	
    return (makePassword($inPassword) == $dbPassword);
}

/**
 * 获取mysql 版本
 * @return string
 */
function getMysqlVersion() {

    $conn = mysqli_connect(
        config('database.hostname') . ":" . config('database.hostport'),
        config('database.username'),
        config('database.password'),
        config('database.database')
    );

    return mysqli_get_server_info($conn);
}

/**
 * 生成layui子孙树
 * @param $data
 * @return array
 */
function makeTree($data) {

    $res = [];
    $tree = [];

    // 整理数组
    foreach ($data as $key => $vo) {
        $res[$vo['id']] = $vo;
        $res[$vo['id']]['children'] = [];
    }
    unset($data);

    // 查询子孙
    foreach ($res as $key => $vo) {
        if($vo['pid'] != 0){
            $res[$vo['pid']]['children'][] = &$res[$key];
        }
    }

    // 去除杂质
    foreach ($res as $key => $vo) {
        if($vo['pid'] == 0){
            $tree[] = $vo;
        }
    }
    unset($res);

    return $tree;
}

/**
 * 打印调试函数
 * @param $data
 */
function dump($data) {

    echo "<pre>";
    print_r($data);
}

/**
 * 标准返回
 * @param $code
 * @param $data
 * @param $msg
 * @return \think\response\Json
 */
function reMsg($code, $data, $msg) {

    return json(['code' => $code, 'data' => $data, 'msg' => $msg]);
}

/**
 * model返回标准函数
 * @param $code
 * @param $data
 * @param $msg
 * @return array
 */
function modelReMsg($code, $data, $msg) {

    return ['code' => $code, 'data' => $data, 'msg' => $msg];
}


/**
 * 根据ip定位
 * @param $ip
 * @return string
 * @throws Exception
 */
function getLocationByIp($ip)
{
    $ip2region = new \Ip2Region();
    $info = $ip2region->btreeSearch($ip);

    $info = explode('|', $info['region']);

    $address = '';
    foreach($info as $vo) {
        if('0' !== $vo) {
            $address .= $vo . '-';
        }
    }

    return rtrim($address, '-');
}

/**
 * 按钮检测
 * @param $input
 * @return bool
 */
function buttonAuth($input)
{
    $authModel = Auth::instance();
    return  $authModel->authCheck($input, session('admin_role_id'));
}

/**
 * curl 请求
 * @param $input
 * @return bool
 */
function curlRequest($url, $method='get', $data=null, $https=false){
    $ch = curl_init();//初始化
    curl_setopt($ch, CURLOPT_URL, $url);//访问的URL
    curl_setopt($ch, CURLOPT_HEADER, false);//设置需要头信息
    //curl模拟头部信息
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
		'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',
	));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//只获取页面内容，但不输出
    if($https){
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//https请求 不验证证书 
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//https请求 不验证HOST
    }
    // curl_setopt($ch,CURLOPT_ENCODING,'gzip');//百度返回的内容进行了gzip压缩,需要用这个设置解析
    if($method == 'post'){
        curl_setopt($ch, CURLOPT_POST, true);//请求方式为post请求
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//请求数据
    }
    $result = curl_exec($ch);//执行请求
    curl_close($ch);//关闭curl，释放资源
    $result = mb_convert_encoding($result, 'utf-8', 'GBK,UTF-8,ASCII,gb2312');//百度默认编码是gb2312 这个设置转化为utf8编码
    return $result;
}

/**
 * 随机UA
 * @param $input
 * @return bool
 */
function randUA(){
    $user_agent = array(
      "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1",
      "Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11",
      "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6",
      "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1090.0 Safari/536.6",
      "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/19.77.34.5 Safari/537.1",
      "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.9 Safari/536.5",
      "Mozilla/5.0 (Windows NT 6.0) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.36 Safari/536.5",
      "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
      "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
      "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_0) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
  
      "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3",
      "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3",
      "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
      "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
      "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
      "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.0 Safari/536.3",
      "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24",
      "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24",
      "Mozilla/5.0 (Macintosh; U; Mac OS X Mach-O; en-US; rv:2.0a) Gecko/20040614 Firefox/3.0.0 ",
      "Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10.5; en-US; rv:1.9.0.3) Gecko/2008092414 Firefox/3.0.3",
  
      "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.1) Gecko/20090624 Firefox/3.5",
      "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.14) Gecko/20110218 AlexaToolbar/alxf-2.0 Firefox/3.6.14",
      "Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10.5; en-US; rv:1.9.2.15) Gecko/20110303 Firefox/3.6.15",
      "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0.1) Gecko/20100101 Firefox/4.0.1",
      "Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11",
      "Opera/9.80 (Android 2.3.4; Linux; Opera mobi/adr-1107051709; U; zh-cn) Presto/2.8.149 Version/11.10",
      "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/531.21.8 (KHTML, like Gecko) Version/4.0.4 Safari/531.21.10",
      "Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US) AppleWebKit/533.17.8 (KHTML, like Gecko) Version/5.0.1 Safari/533.17.8",
      "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.19.4 (KHTML, like Gecko) Version/5.0.2 Safari/533.18.5",
      "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0",
  
      "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)",
      "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)",
      "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"
    );
    $rand_key = mt_rand(0,32);
    return $user_agent[$rand_key];
  }


  /**
 * 日期拆分
 * @param
 * @return array
 */
function dateSplit($startDate, $endDate){
    $flag = 'day';
    $format = 'Y-m-d';
    if(substr_count($startDate, '-') == 1){
        $flag = 'month';
        $format = 'Y-m';
    }
    $list[$startDate] = 0;
    while(1){
        $startDate = date($format, strtotime("$startDate +1 $flag"));
        if(strtotime($startDate) >= strtotime($endDate)){
            break;
        }
        $list[$startDate] = 0;
    }
    return $list;
}


  /**
 * 判断客户端
 * @param
 * @return array
 */
function is_mobile($ua) {
    if (empty($ua)) {
        $is_mobile = -1;
    } elseif ( strpos($ua, 'Mobile') !== false 
            || strpos($ua, 'Android') !== false
            || strpos($ua, 'Phone') !== false
            || strpos($ua, 'iPad') !== false
            || strpos($ua, 'Tablet') !== false
            || strpos($ua, 'Silk/') !== false
            || strpos($ua, 'Kindle') !== false
            || strpos($ua, 'BlackBerry') !== false
            || strpos($ua, 'Opera Mini') !== false
            || strpos($ua, 'Opera Mobi') !== false ) {
        $is_mobile = 2;
    }else{
        $is_mobile = 1;
    }
    return $is_mobile;
}


  /**
 * 获取关键词
 * @param
 * @return array
 */
function getKeyword($eqid){
    if (empty($eqid)) {
        return;
    }
    $url = 'http://xxx.com/api/referer_api.php?token=CRjAM61jieCidQPPtlf9&eqid='.$eqid;
    $text = curlRequest($url);
    if(strpos($text, $eqid)){
        $arr = json_decode($text, true);
        return urldecode($arr['wd']);
    }
    return;
}

  /**
 * 获取关键词
 * @param
 * @return array
 */
function getKeyword2($link){
    if (empty($link)) {
        return;
    }
    $url = 'http://www.yiqixxx.com/';
    $data = array(
        'password' => '11111111111111111111111111111111',
        'link' => $link,
    );
    $html = curlRequest($url, 'post', $data);
    if(strpos($html, '解析结果')){
        preg_match('/<li>(.*?)<\/li>/', $html, $res);
        return $res[1];
    }
    return;
}

  /**
 * 修改配置
 * @param
 * @return array
 */
function editConfig($arr = [] ,$user='admin')
{
    if (is_array($arr)) {
        //获取文件名
        $filename = 'system.php';
        //获取配置文件环境变量位置(请确保开启权限,如若报错,请改为绝对路径)
        $filepath = Env::get('CONFIG_PATH'). $filename;
        //判定配置文件是否存在
        if (!file_exists($filepath)  ) {

            if(!fopen($filepath, "w")){
                return 'PermissionError1';
            }
        }
        //判定权限是否足够
        if (!is_writable($filepath)) {
            return 'PermissionError2';
        }
        //遍历整个配置文件
        $conf = include $filepath;
        foreach ($arr as $key => $value) {
            $conf[$key] = $value;
        }
        //记录修改者
        $time = date('Y/m/d H:i:s');
        $str = "<?php\r\n/**\r\n * 由".$user."修改.\r\n * $time\r\n */\r\nreturn [\r\n";
        //写入配置文件
        foreach ($conf as $key => $value) {
            if(is_array($value)){
                $str.="\t'$key'=>[\r\n";
                foreach ($value as $ikey=>$r) {
                    if(is_numeric($ikey)){
                        $str .= "\t\t'$r',";
                        $str .= "\r\n";
                    }else{
                        $str .= "\t\t'$ikey' => '$r',";
                        $str .= "\r\n";
                    }

                }
                $str = rtrim($str,',');
                $str .= "\t],"."\r\n";
            } else{
                $str .= "\t'$key' => '$value',";
                $str .= "\r\n";
            }
        }
        $str .= '];';
        //关闭文件
        $result = file_put_contents($filepath, $str);
        if($result){
            return '设置成功';
        } else {
            return $result;
        }

    } else {
        return 'error';
    }
}